import React, { useState, useEffect } from 'react';
import { Table, Button, Card, Modal, Select, Tag, message, Space, Typography, Descriptions } from 'antd';
import { EyeOutlined, TruckOutlined } from '@ant-design/icons';
import { Order } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';

const { Title } = Typography;

const OrderManagement: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [statusFilter, setStatusFilter] = useState<string>('all');

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    const savedOrders = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
    setOrders(savedOrders);
  };

  const saveOrders = (newOrders: Order[]) => {
    Storage.set(STORAGE_KEYS.ORDERS, newOrders);
    setOrders(newOrders);
  };

  const getStatusInfo = (status: Order['status']) => {
    const statusMap = {
      pending: { text: '待付款', color: 'orange' },
      paid: { text: '已付款', color: 'blue' },
      shipped: { text: '已发货', color: 'cyan' },
      delivered: { text: '已送达', color: 'green' },
      cancelled: { text: '已取消', color: 'red' }
    };
    return statusMap[status];
  };

  const handleStatusChange = (orderId: string, newStatus: Order['status']) => {
    const newOrders = orders.map(order =>
      order.id === orderId
        ? { ...order, status: newStatus, updatedAt: new Date().toISOString() }
        : order
    );
    saveOrders(newOrders);
    message.success('订单状态更新成功');
  };

  const handleViewDetail = (order: Order) => {
    setSelectedOrder(order);
    setDetailModalVisible(true);
  };

  const handleShip = (orderId: string) => {
    handleStatusChange(orderId, 'shipped');
  };

  const filteredOrders = orders.filter(order => 
    statusFilter === 'all' || order.status === statusFilter
  );

  const columns = [
    {
      title: '订单号',
      dataIndex: 'id',
      key: 'id',
      render: (id: string) => id.slice(0, 12) + '...',
    },
    {
      title: '收货人',
      dataIndex: 'address',
      key: 'address',
      render: (address: any) => address.name,
    },
    {
      title: '商品数量',
      dataIndex: 'items',
      key: 'items',
      render: (items: any[]) => `${items.length} 件`,
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => `¥${amount.toFixed(2)}`,
      sorter: (a: Order, b: Order) => a.totalAmount - b.totalAmount,
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: Order['status']) => {
        const statusInfo = getStatusInfo(status);
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      },
    },
    {
      title: '下单时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
      sorter: (a: Order, b: Order) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Order) => (
        <Space size="small">
          <Button
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          {record.status === 'paid' && (
            <Button
              size="small"
              type="primary"
              icon={<TruckOutlined />}
              onClick={() => handleShip(record.id)}
            >
              发货
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <Title level={2}>订单管理</Title>
        <Select
          value={statusFilter}
          onChange={setStatusFilter}
          style={{ width: 120 }}
        >
          <Select.Option value="all">全部状态</Select.Option>
          <Select.Option value="pending">待付款</Select.Option>
          <Select.Option value="paid">已付款</Select.Option>
          <Select.Option value="shipped">已发货</Select.Option>
          <Select.Option value="delivered">已送达</Select.Option>
          <Select.Option value="cancelled">已取消</Select.Option>
        </Select>
      </div>

      <Card>
        <Table
          columns={columns}
          dataSource={filteredOrders}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      {/* 订单详情模态框 */}
      <Modal
        title="订单详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedOrder && (
          <div>
            <Descriptions title="订单信息" bordered>
              <Descriptions.Item label="订单号">{selectedOrder.id}</Descriptions.Item>
              <Descriptions.Item label="订单状态">
                <Tag color={getStatusInfo(selectedOrder.status).color}>
                  {getStatusInfo(selectedOrder.status).text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="订单金额">¥{selectedOrder.totalAmount.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="收货人">{selectedOrder.address.name}</Descriptions.Item>
              <Descriptions.Item label="联系电话">{selectedOrder.address.phone}</Descriptions.Item>
              <Descriptions.Item label="收货地址" span={2}>
                {`${selectedOrder.address.province} ${selectedOrder.address.city} ${selectedOrder.address.district} ${selectedOrder.address.detail}`}
              </Descriptions.Item>
              <Descriptions.Item label="下单时间">{new Date(selectedOrder.createdAt).toLocaleString()}</Descriptions.Item>
              <Descriptions.Item label="更新时间">{new Date(selectedOrder.updatedAt).toLocaleString()}</Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: 24 }}>
              <Title level={4}>商品清单</Title>
              <Table
                size="small"
                columns={[
                  {
                    title: '商品',
                    dataIndex: 'product',
                    render: (product: any) => (
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img
                          src={product.image}
                          alt={product.name}
                          style={{ width: 40, height: 40, objectFit: 'cover', marginRight: 8 }}
                        />
                        <span>{product.name}</span>
                      </div>
                    ),
                  },
                  {
                    title: '单价',
                    dataIndex: 'price',
                    render: (price: number) => `¥${price}`,
                  },
                  {
                    title: '数量',
                    dataIndex: 'quantity',
                  },
                  {
                    title: '小计',
                    render: (_: any, record: any) => `¥${(record.price * record.quantity).toFixed(2)}`,
                  },
                ]}
                dataSource={selectedOrder.items}
                rowKey="id"
                pagination={false}
              />
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default OrderManagement;
